package com.shuqi.database.dbimport;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;
import com.shuqi.common.utils.BookBagUtil;
import com.shuqi.common.utils.MyUrlTools;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.model.bean.BookContentInfo;
import com.shuqi.model.parse.parser.BookContentLocalAppBagParser.BookBagCatalogHandler;
import com.shuqi.model.parse.parser.XMLHelper;

public class ImportOldDataHeper {
    public static final String TAG = "ImportOldDataHeper";

    private static ImportOldDataHeper mInstance;

    SQLiteDatabase mSQLiteDatabase;

    private ImportOldDataHeper() {
        mSQLiteDatabase =
                ShuqiApplication.getContext().openOrCreateDatabase("shuqi2.db",
                        Context.MODE_PRIVATE, null);
    }

    public static synchronized ImportOldDataHeper getInstance() {
        if (mInstance == null) {
            mInstance = new ImportOldDataHeper();
        }
        return mInstance;
    }



    public List<BookMarkInfo> readOldBookMarkinfoList() {
        if (mSQLiteDatabase != null) {
            Cursor cursor = null;
            try {
                String querySql = "select * from book_mark where type in ('1','3','4','7')";
                cursor = mSQLiteDatabase.rawQuery(querySql, null);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (cursor != null) {
                List<BookMarkInfo> list = new ArrayList<BookMarkInfo>();
                try {
                    while (cursor.moveToNext()) {
                        String markTitle = cursor.getString(cursor.getColumnIndex("mark_title"));
                        String percent = cursor.getString(cursor.getColumnIndex("percent"));
                        String markContent =
                                cursor.getString(cursor.getColumnIndex("mark_content"));
                        String bookId = cursor.getString(cursor.getColumnIndex("book_id"));
                        String chapterId = cursor.getString(cursor.getColumnIndex("chapter_id"));
                        String type = cursor.getString(cursor.getColumnIndex("type"));
                        String flag = cursor.getString(cursor.getColumnIndex("flag"));
                        String imgUrl = cursor.getString(cursor.getColumnIndex("img_url"));
                        String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
                        String chapterFileName =
                                cursor.getString(cursor.getColumnIndex("chapter_filename"));
                        String fileName = cursor.getString(cursor.getColumnIndex("filename"));
                        String param1 = cursor.getString(cursor.getColumnIndex("param1"));
                        String param2 = cursor.getString(cursor.getColumnIndex("param2"));
                        // String isUpdated = cursor.getString(cursor.getColumnIndex("isupdated"));
                        int numChapter = cursor.getInt(cursor.getColumnIndex("numchapter"));
                        String uid = cursor.getString(cursor.getColumnIndex("account"));

                        int bookType = Integer.parseInt(type);
                        BookMarkInfo info = new BookMarkInfo();
                        info.setBookName(markTitle);
                        info.setPercent(percent);
                        info.setBookId(bookId);
                        info.setChapterId(chapterId);
                        info.setBookType(Integer.parseInt(type));
                        try {
                            info.setDeleteFlag(Integer.parseInt(flag));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (!TextUtils.isEmpty(createTime)) {
                            long time = Long.parseLong(createTime);
                            if (createTime.length() == 10) {
                                time = time * 1000;
                            }
                            info.setUpdateTime(time);
                        }

                        if (bookType == BookMarkInfo.TYPE_LOCAL_BOOKMARK) {
                            // 本地书签
                            info.setLocalImageUrl();
                        } else {
                            info.setBookCoverImgUrl(imgUrl);
                        }

                        info.setUserId(uid);

                        info.setTotalChapter(numChapter);
                        try {
                            int bookReadbyte = 0;
                            if (!TextUtils.isEmpty(param1)) {
                                bookReadbyte = Integer.parseInt(param1);
                            }
                            info.setBookReadByte(bookReadbyte < 0 ? 0 : bookReadbyte);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            int totalByte = 0;
                            if (!TextUtils.isEmpty(param2)) {
                                totalByte = Integer.parseInt(param2);
                            }
                            info.setBookTotalByte(totalByte < 0 ? 0 : totalByte);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        info.setChapterName(markContent);

                        // fileName 处理
                        if (bookType == BookMarkInfo.TYPE_OLD_WEB_BOOKMARK) {
                            info.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK);
                            info.setFilePath(fileName);
                            String cid = MyUrlTools.getChapterIdFromWebBookMarkUrl(fileName);
                            String sourceId = MyUrlTools.getSourceIdFromWebBookMarkUrl(fileName);
                            info.setChapterId(cid);
                            info.setSourceId(sourceId);
                        } else if (bookType == BookMarkInfo.TYPE_LOCAL_BOOKMARK
                                || bookType == BookMarkInfo.TYPE_OLD_BAG_BOOKMARK) {
                            info.setFilePath(fileName);

                            if (!TextUtils.isEmpty(fileName)) {
                                final int index = fileName.lastIndexOf(".");

                                if (fileName.length() > (index + 1)) {
                                    final String extention = fileName.substring(index + 1);
                                    // 7.x将umd,txt将readbyte存放到了param2中，这块是补丁
                                    if ("umd".equalsIgnoreCase(extention)) {
                                        // /2是转换成字节数
                                        info.setBookReadByte(info.getBookTotalByte() * 2);
                                        info.setBookTotalByte(0);
                                    } else if ("txt".equalsIgnoreCase(extention)) {
                                        // txt 特殊处理
                                        info.setBookTotalByte(0);
                                        info.setBookReadByte(0);
                                        try {
                                            File file = new File(fileName);
                                            long size = file.length();
                                            info.setBookReadByte((int) (size
                                                    * Float.valueOf(percent) * 0.01));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }

                        if (bookType == BookMarkInfo.TYPE_OLD_BAG_BOOKMARK) {
                            // fix bookbag
                            fixBookBag(info, chapterFileName);
                        }

                        list.add(info);
                    }
                    return list;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    cursor.close();
                }
            }
        }
        return null;

    }

    private BookBagCatalogHandler mCatalogHandler = null;

    private void fixBookBag(BookMarkInfo info, String chapterFileName) {
        if (info == null) {
            return;
        }
        if (mCatalogHandler == null) {
            mCatalogHandler = new BookBagCatalogHandler();
        }
        int cid = 0;
        try {
            cid = Integer.parseInt(chapterFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long time = System.currentTimeMillis();
        String filePath = info.getFilePath();
        filePath = Config.BOOKBAG_PATH + "/" + filePath;
        ByteArrayOutputStream as = BookBagUtil.decode2Zip(filePath, ConfigVersion.SN);
        ByteArrayInputStream is = BookBagUtil.unzip(as, "chapterinfo.xml");
        XMLHelper.doInputSteamParse(mCatalogHandler, is);
        List<BookContentInfo> list = mCatalogHandler.getParsedData();
        if (list != null && list.size() > 0 && cid < list.size()) {
            info.setChapterId(list.get(cid).getCurChapterCid());
        }
    }

    public void release() {
        mSQLiteDatabase.close();
        mCatalogHandler = null;
    }
}
